package com.exde.wcsiapp.autoupdate;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by yangdi on 2018/6/13.
 */

public class Utils {
    /**
     * 获取版本号
     *
     * @throws PackageManager.NameNotFoundException
     */
    public static String getVersionName(Context context) throws PackageManager.NameNotFoundException {
        // 获取packagemanager的实例
        PackageManager packageManager = context.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
        String version = packInfo.versionName;
        return version;
    }

    /**
     * 版本号比较
     *0代表相等，1代表version1大于version2，-1代表version1小于version2
     * @param version1
     * @param version2
     * @return
     */
    public static int compareVersion(String version1, String version2) {
        if (version1.equals(version2)) {
            return 0;
        }
        String[] version1Array = version1.split("\\.");
        String[] version2Array = version2.split("\\.");
        int index = 0;
        // 获取最小长度值
        int minLen = Math.min(version1Array.length, version2Array.length);
        int diff = 0;
        // 循环判断每位的大小
        while (index < minLen
                && (diff = Integer.parseInt(version1Array[index])
                - Integer.parseInt(version2Array[index])) == 0) {
            index++;
        }
        if (diff == 0) {
            // 如果位数不一致，比较多余位数
            for (int i = index; i < version1Array.length; i++) {
                if (Integer.parseInt(version1Array[i]) > 0) {
                    return 1;
                }
            }

            for (int i = index; i < version2Array.length; i++) {
                if (Integer.parseInt(version2Array[i]) > 0) {
                    return -1;
                }
            }
            return 0;
        } else {
            return diff > 0 ? 1 : -1;
        }
    }


    private static VersionInfoBean versionInfoBean = null;

    private static String success = "";

    public static VersionInfoBean getVersionInfoBean(){
        return versionInfoBean;
    }


    public  void checkVersion() {
        final long startTime=System.currentTimeMillis();
        versionInfoBean = null;
        success = "begin";
        new Thread(){
            public void run(){
                HttpURLConnection conn=null;
                Message msg=Message.obtain();
                try {
                    URL url=new URL("http://192.168.0.105:8888/wcsi/ui/download/getVersion");
                    conn=(HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);
                    conn.connect();

                    int responseCode=conn.getResponseCode();
                    if(responseCode==200){
                        InputStream inputStream=conn.getInputStream();

                        ByteArrayOutputStream out=new ByteArrayOutputStream();
                        int len=0;
                        byte []buffer=new byte[1024];
                        while((len=inputStream.read(buffer))!=-1){
                            out.write(buffer, 0, len);
                        }
                        inputStream.close();
                        out.close();

                        String result = out.toString();
                        Log.d("MainUtils", "VersionResult:"+result);

                        try {
                            JSONObject jo = new JSONObject(result);
                            success=jo.getString("success");
                            Log.d("MainUtils", "success:"+success);
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        if(success.equals("true")){

                            Gson gson = new Gson();
                            versionInfoBean = gson.fromJson(result,VersionInfoBean.class);
                        }else{
                            success = "end";
                        }
                    }
                }catch (MalformedURLException e) {
                    //url错误
                    e.printStackTrace();
                }catch (IOException e) {
                    //网络错误
                    e.printStackTrace();
                }finally{
                    long endTime=System.currentTimeMillis();
                    long timeUsed=endTime-startTime;
                    if(timeUsed<2000){
                        try {
                            Thread.sleep(2000-timeUsed);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    if(conn!=null){
                        //关闭网络连接
                        conn.disconnect();
                    }
                }
            }
        }.start();
    }
}
